<?php
/**
 * XiaoYuanMenSuo-PHP
 * ==================================================================
 * CopyRight © 2017-2099 广州米袋软件有限公司
 * 官网地址：http://www.mdsoftware.cn
 * 售后技术支持：15017566075
 * ------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下
 * 对本程序代码进行修改和使用；不允许对本程序代码以任何目的的再发布。
 * ==================================================================
 *
 * @Author ZHC(codecookies@163.com)
 * @Date 2021-12-16 16:44 星期四
 * @Version 1.0
 */

namespace app\controller\admin;


use app\model\AdminCheckInRecord;
use app\model\AdminSchoolRkeRecord;
use app\model\AdminStaff;
use app\util\ExcelHandle;
use app\util\ReturnCode;
use think\Response;

class Record extends Base
{

    /**
     * 学校门禁进出记录列表
     * @Author ZHC(codecookies@163.com)
     * @Date 2021-12-17 12:28 星期五
     * @Version 1.0
     * @return Response
     */
    public function index(): Response {
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $data = input('get.');
        $limit = $data['size'] ?? config('apiadmin.ADMIN_LIST_DEFAULT');
        $start = $data['page'] ?? 1;
        $student_no = $data['student_no'] ?? '';
        $student_name = $data['student_name'] ?? '';
        $phone = $data['phone'] ?? '';
        $card_type = $data['card_type'] ?? '';
        $act_index = $data['act_index'] ?? '';
        $status = $data['status'] ?? '';
        $date = $data['date'] ?? '';

        $where = [];
        $obj = (new AdminSchoolRkeRecord())->alias('AdminSchoolRkeRecord');
        $staff_where = [];
        if ($student_no) {
            $staff_where[] = ['student_no', 'like', '%' . $student_no . '%'];
        }
        if ($student_name) {
            $staff_where[] = ['name', 'like', '%' . $student_name . '%'];
        }
        if ($phone) {
            $staff_where[] = ['phone', 'like', '%' . $phone . '%'];
        }
        if ($school_id) {
            array_push($where, ['AdminSchoolRkeRecord.school_id', '=', $school_id]);
        }
        if ($status) {
            array_push($where, ['AdminSchoolRkeRecord.acs_res', '=', $status]);
        }
        if ($card_type) {
            array_push($where, ['AdminSchoolRkeRecord.card_type', '=', $card_type]);
        }
        if ($act_index) {
            array_push($where, ['AdminSchoolRkeRecord.act_index', '=', $act_index]);
        }
        if (!empty($date) && !is_array($date)) {
            $date = explode( ",", $date);
        }
        if (!empty($date) && array_filter($date)){
            $start_date = $date[0] ? $date[0] : '';
            $end_date = $date[1] ? $date[1] : '';
            if ($start_date){
                array_push($where, ['AdminSchoolRkeRecord.create_time', '>=', strtotime($start_date)]);
            }
            if ($end_date){
                array_push($where, ['AdminSchoolRkeRecord.create_time', '<=', strtotime($end_date)]);
            }
        }

        $listObj = $obj
            ->hasWhere('staff', $staff_where)
            ->where($where)->with(['staff','school'])
            ->order('AdminSchoolRkeRecord.srr_id', 'DESC')
            ->append(['acs_res_text','act_index_text','serial_type_text'])
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();
        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    /**
     * 签到记录
     * @Author ZHC(codecookies@163.com)
     * @Date 2021-12-17 12:30 星期五
     * @Version 1.0
     * @return Response
     */
    public function checkIn(): Response{
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords');
        $date = $this->request->get('date');
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $school_name = $this->request->get('school_name', '');

        $obj = (new AdminCheckInRecord())->alias('AdminCheckInRecord');
        $where = [];
        if ($school_id) {
            array_push($where, ['AdminCheckInRecord.school_id', '=', $school_id]);
        }
        if ($school_name) {
            $obj = $obj->hasWhere('school', function ($query) use ($school_name) {
                $query->where('name', 'like', '%' . $school_name . '%');
            });
        }
        if ($keywords) {
            $obj = $obj->hasWhere('staff', function ($query) use ($keywords) {
                    $query->where('name', 'like', '%' . $keywords . '%');
                });
        }
        if ($date && is_array($date)){
            $start_date = $date[0] ? $date[0] : '';
            $end_date = $date[1] ? $date[1] : '';

            if ($start_date){
                array_push($where, ['AdminCheckInRecord.create_time', '>=', strtotime($start_date)]);
            }
            if ($end_date){
                array_push($where, ['AdminCheckInRecord.create_time', '<=', strtotime($end_date)]);
            }
        }

        $listObj = $obj->where($where)->with(['staff','school'])
            ->order('AdminCheckInRecord.id', 'DESC')
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    /**
     * @func download
     * @desc 导出文件
     * @return \think\Response
     * @Time: 2021/12/20 11:18
     */
    public function download(): Response  {
        $titles = [['id' => '序号'],['school_name' => '学校名称']
            ,['serial'=>'设备序列号'],['card_type_text'=>'开始方式']
            ,['student_no'=>'学号'],['staff_name'=>'姓名'],['phone'=>'手机号']
            ,['act_index_text'=>'进出方向'],['acs_res_text' => '开门状态']
            ,['staff_type_text'=>'操作人身份'],['create_time' => '开锁时间']];

        $school_id = $this->request->get('school_id');
        $data = input('get.');
        $student_no = $data['student_no'] ?? '';
        $student_name = $data['student_name'] ?? '';
        $phone = $data['phone'] ?? '';
        $card_type = $data['card_type'] ?? '';
        $act_index = $data['act_index'] ?? '';
        $status = $data['status'] ?? '';
        $date = $data['date'] ?? '';

        try {

            $where = [];
            $obj = (new AdminSchoolRkeRecord())->alias('AdminSchoolRkeRecord');
            $staff_where = [];
            if ($student_no) {
                $staff_where[] = ['student_no', 'like', '%' . $student_no . '%'];
            }
            if ($student_name) {
                $staff_where[] = ['name', 'like', '%' . $student_name . '%'];
            }
            if ($phone) {
                $staff_where[] = ['phone', 'like', '%' . $phone . '%'];
            }
            if ($school_id) {
                array_push($where, ['AdminSchoolRkeRecord.school_id', '=', $school_id]);
            }
            if ($status) {
                array_push($where, ['AdminSchoolRkeRecord.acs_res', '=', $status]);
            }
            if ($card_type) {
                array_push($where, ['AdminSchoolRkeRecord.card_type', '=', $card_type]);
            }
            if ($act_index) {
                array_push($where, ['AdminSchoolRkeRecord.act_index', '=', $act_index]);
            }
            if (!empty($date) && !is_array($date)) {
                $date = explode( ",", $date);
            }
            if (!empty($date) && array_filter($date)){
                $start_date = $date[0] ? $date[0] : '';
                $end_date = $date[1] ? $date[1] : '';
                if ($start_date){
                    array_push($where, ['AdminSchoolRkeRecord.create_time', '>=', strtotime($start_date)]);
                }
                if ($end_date){
                    array_push($where, ['AdminSchoolRkeRecord.create_time', '<=', strtotime($end_date)]);
                }
            }

            $exportData = [];
            $len        = 1;
            $page = 1;    // 页面
            $pageSize = 1000;    //每页条数
            while(
            $listObj = (new AdminSchoolRkeRecord())->alias('AdminSchoolRkeRecord')
                ->hasWhere('staff', $staff_where)
                ->where($where)->with(['staff', 'school'])
                ->order('AdminSchoolRkeRecord.srr_id', 'DESC')
                ->append(['acs_res_text', 'act_index_text'])
                ->page($page)->limit($pageSize)->select()->toArray()
            )
            {
                foreach ($listObj as $datum) {
                    $datum['student_no'] = $datum['staff']['student_no'];
                    $datum['staff_name'] = $datum['staff']['name'];
                    $datum['phone'] = $datum['staff']['phone'];
                    $datum['staff_type_text'] = AdminStaff::TYPE_ARR[$datum['staff']['type']];
                    $datum['card_type_text'] = AdminSchoolRkeRecord::CARD_TYPE[$datum['card_type']];
                    $datum['serial'] .= "\t";
                    $datum['act_index_text'] .= "\t";
                    $newItem               = array_merge(['id' => $len], $datum);
                    array_push($exportData, $newItem);
                    $len++;
                }
                $page++;
                if ($page > 20) {
                    break;
                }
            }
            ExcelHandle::downLoadExcel('进出记录' . date('YmdHi'), $titles, $exportData);
        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }

    /**
     * @func download
     * @desc 导出文件
     * @return \think\Response
     * @Time: 2021/12/20 11:18
     */
    public function checkInDownload(): Response  {
        $titles = [['id' => '序号'],['school_name' => '学校名称'],['staff_name'=>'姓名'],['address'=>'签到地址'],['create_time' => '签到时间']];

        $keywords = $this->request->get('keywords');
        $date = $this->request->get('date');
        $school_id = $this->request->get('school_id', 0);
        $school_name = $this->request->get('school_name', '');

        try {
            $obj = (new AdminCheckInRecord())->alias('AdminCheckInRecord');
            $where = [];
            if ($school_id) {
                array_push($where, ['AdminCheckInRecord.school_id', '=', $school_id]);
            }
            if ($school_name) {
                $obj = $obj->hasWhere('school', function ($query) use ($school_name) {
                    $query->where('name', 'like', '%' . $school_name . '%');
                });
            }
            if ($keywords) {
                $obj = $obj->hasWhere('staff', function ($query) use ($keywords) {
                    $query->where('name', 'like', '%' . $keywords . '%');
                });
            }
            if ($date){
                $date = explode(',', $date);
                $start_date = $date[0] ? $date[0] : '';
                $end_date = $date[1] ? $date[1] : '';

                if ($start_date){
                    array_push($where, ['AdminCheckInRecord.create_time', '>=', strtotime($start_date)]);
                }
                if ($end_date){
                    array_push($where, ['AdminCheckInRecord.create_time', '<=', strtotime($end_date)]);
                }
            }

            $listObj    = $obj->where($where)->with(['staff', 'school'])
                ->order('AdminCheckInRecord.id', 'DESC')
                ->select()->toArray();
            $exportData = [];
            $len        = 1;
            foreach ($listObj as $datum) {
                $datum['staff_name'] .= "\t";
                $newItem               = array_merge(['id' => $len], $datum);
                array_push($exportData, $newItem);
                $len++;
            }
            ExcelHandle::downLoadExcel('签到记录' . date('YmdHi'), $titles, $exportData);
        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }
}